import { watch, CSSProperties, watchEffect, ref, unref, getCurrentInstance } from 'vue';
import { useDraggable } from '@vueuse/core';

export function userModalDrag () {

  const modalTitleRef = ref<HTMLElement>(null);
  const { x, y, isDragging } = useDraggable(modalTitleRef);


  let startX = $ref<number>(0);
  let startY = $ref<number>(0);
  let startedDrag = $ref(false);
  let transformX = $ref(0);
  let transformY = $ref(0);
  let preTransformX = $ref(0);
  let preTransformY = $ref(0);
  let dragRect = $ref({ left: 0, right: 0, top: 0, bottom: 0 });

  watch([x, y], () => {
    if (!startedDrag) {
      startX = x.value;
      startY = y.value;
      const bodyRect = document.body.getBoundingClientRect();
      const titleRect = modalTitleRef.value?.getBoundingClientRect();
      dragRect.right = bodyRect.width - titleRect?.width;
      dragRect.bottom = bodyRect.height - titleRect?.height;
      preTransformX = transformX;
      preTransformY = transformY;
    }
    startedDrag = true;
  });

  watch(isDragging, () => {
    if (!isDragging) {
      startedDrag = false;
    }
  });

  watchEffect(() => {
    if (startedDrag) {
      transformX =
        preTransformX +
        Math.min(Math.max(dragRect.left, x.value), dragRect.right) -
        startX;
      transformY =
        preTransformY +
        Math.min(Math.max(dragRect.top, y.value), dragRect.bottom) -
        startY;
    }
  });

  const transformStyle = $computed<CSSProperties>(() => {
    return {
      transform: `translate(${transformX}px, ${transformY}px)`,
    };
  });

  return {
    transformX,
    transformY,
    transformStyle
  };
}
